package com.arraymasterx.service;

import com.arraymasterx.algorithm.search.BinarySearch;
import com.arraymasterx.config.AlgorithmConfig;
import com.arraymasterx.model.request.SearchRequest;
import com.arraymasterx.model.response.SearchResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SearchService {

    private final BinarySearch binarySearch;
    private final AlgorithmConfig algorithmConfig;

    @Autowired
    public SearchService(BinarySearch binarySearch, AlgorithmConfig algorithmConfig) {
        this.binarySearch = binarySearch;
        this.algorithmConfig = algorithmConfig;
    }

    public SearchResponse binarySearch(SearchRequest request) {
        validateInput(request.getArray());

        int result = binarySearch.search(request.getArray(), request.getTarget());
        return new SearchResponse(result);
    }

    private void validateInput(int[] array) {
        if (array == null) {
            throw new IllegalArgumentException("Input array cannot be null");
        }

        if (array.length > algorithmConfig.getSearch().getMaxArraySize()) {
            throw new IllegalArgumentException(
                    "Array size exceeds maximum allowed size: " + algorithmConfig.getSearch().getMaxArraySize());
        }
    }
}